using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls;
using jqMvcGrid.Models;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.MobileControls;

namespace jqMvcGrid.Controllers
{
    public class ProductsController : Controller
    {
        private IProductRepository _repository = new ProductRepository();

        //
        // GET: /Products/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult List(int page, int rows, string search, string sidx, string sord, int? categoryId)
        {
            string key = "{B1D2D0D8-9813-4072-A2F8-E304A0AA0FC8}";
            var repository = new ProductRepository();
            if (categoryId.HasValue)
            {
                var model = from entity in repository.Index(categoryId.Value).OrderBy(sidx + " " + sord)
                            select new
                            {
                                Edit = "<a style='color:#5c87b2' href='" + "Products/Edit/" + entity.ProductID + "'>Edit</a>",
                                Details = "<a style='color:#5c87b2' href='" + "Products/Details/" + entity.ProductID + "'>Details</a>",
                                ProductID = entity.ProductID,
                                ProductName = entity.ProductName,
                                UnitPrice = entity.UnitPrice,
                                Discontinued = entity.Discontinued == true ? "<input type='checkbox' checked='checked' disabled='disabled' />" : "<input type='checkbox' disabled='disabled' />"
                            };
                return Json(model.ToJqGridData(page, rows, null, search,
                    new[] { "ProductName" }));
            }
            else
            {
                var products = repository.Index().ToList();
                products.AddRange(NewProductRows(6));
                var model = from entity in products.AsQueryable().OrderBy(sidx + " " + sord)
                            select new
                            {
                                Edit = "<a style='color:#5c87b2' href='" + "Products/Edit/" + entity.ProductID + "'>Edit</a>",
                                Details = "<a style='color:#5c87b2' href='" + "Products/Details/" + entity.ProductID + "'>Details</a>",
                                ProductID = entity.ProductID,
                                ProductName = entity.ProductName,
                                UnitPrice = entity.UnitPrice,
                                Discontinued = entity.Discontinued == true ? "<input type='checkbox' checked='checked' disabled='disabled' />" : "<input type='checkbox' disabled='disabled' />"
                            };
                return Json(model.ToJqGridData(page, rows, null, search,
                    new[] { "ProductName" }));
            }
        }

        private IList<Product> NewProductRows(int rows)
        {
            try
            {
                var products = new List<Product>();
                for (int i = 0; i < rows; i++)
                {
                    products.Insert(i, new Product() { ProductID = 0, ProductName = "", SupplierID = 0, CategoryID = 0, QuantityPerUnit = "", UnitPrice = 0.00m, UnitsInStock = 0, UnitsOnOrder = 0, ReorderLevel = 0, Discontinued = false });
                }
                return products;
            }
            catch { return null; }
        }

        public ActionResult ExportToExcel()
        {
            var products = _repository.Index();

            var grid = new GridView();
            grid.DataSource = from p in products
                              select new
                              {
                                  ProductId = p.ProductID,
                                  ProductName = p.ProductName,
                                  UnitPrice = p.UnitPrice,
                                  Discontinued = p.Discontinued
                              };
            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
            Response.ContentType = "application/excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

            return View("Index");
        }

        //
        // GET: /Products/Details/5

        public ActionResult Details(int id)
        {
            return View(_repository.Details(id));
        }

        //
        // GET: /Products/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Products/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Product product, FormCollection collection)
        {
            try
            {
                // Validate
                if (!Validate(product))
                    return View();

                if (_repository.Create(product))
                    return View();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Products/Edit/5

        public ActionResult Edit(int id)
        {
            return View(_repository.Details(id));
        }

        //
        // POST: /Products/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Product product, FormCollection collection)
        {
            try
            {
                // Validate
                if (!Validate(product))
                    return View(product);
                if (product.ProductID == 0)
                    if (!_repository.Create(product))
                        return View(product);
                // Edit
                //if (!_repository.Edit(product))
                //    return View(product);

                // Success
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        protected bool Validate(Product product)
        {
            if (string.IsNullOrEmpty(product.ProductName))
                ModelState.AddModelError("ProductName", "ProductName is required!");
            return ModelState.IsValid;
        }
    }
}
